package com.tiance.web.controller.back;

import com.alibaba.fastjson.JSON;
import com.tiance.constants.CommonConstants;
import com.tiance.dal.dataobject.MemberAuthenticationInfoDO;
import com.tiance.dal.dataobject.MemberDO;
import com.tiance.domainservice.checker.MemberParamsChecker;
import com.tiance.domainservice.domain.MemberAuthenticationInfoDomain;
import com.tiance.domainservice.domain.MemberDomain;
import com.tiance.domainservice.service.MemberAuthService;
import com.tiance.domainservice.service.MemberService;
import com.tiance.domainservice.service.SignInService;
import com.tiance.enums.*;
import com.tiance.exception.BusinessException;
import com.tiance.integration.cache.MapCacheUtil;
import com.tiance.integration.config.CommonProperties;
import com.tiance.integration.wechat.WxUserInfo;
import com.tiance.page.QueryPage;
import com.tiance.utils.BeanConverterUtil;
import com.tiance.vo.MemberAuthenticationInfoVO;
import com.tiance.vo.MemberVO;
import com.tiance.web.aspect.OperatorControllerLog;
import com.tiance.web.controller.base.BackController;
import com.tiance.web.controller.base.FrontController;
import com.tiance.web.controller.common.BaseResponse;
import com.tiance.web.convertor.ModelConvert;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/1/30
 *
 * Description：会员管理
 *
 * Modification History:
 *
 */
@Controller
@RequestMapping(value = "/back/memberCenter")
public class BackMemberController extends BackController {
    private static String LOG_PREFIX ="BackMemberController| 会员控制器===>";



    @Autowired
    private CommonProperties commonProperties;





    @Autowired
    private MemberService     memberService;
    @Autowired
    private MemberAuthService memberAuthService;
    @Autowired
    private SignInService     signInService;

    @RequestMapping(value = "/toGuestList.action",method = RequestMethod.GET)
    @RequiresPermissions("menu:memberCenter:regularMember")
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到普通会员列表页面")
    public String toGuestList() {
        return "/back/memberCenter/guest/guestList";
    }
    @RequestMapping(value = "/toRegularMemberList.action",method = RequestMethod.GET)
    @RequiresPermissions("menu:memberCenter:regularMember")
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到普通会员列表页面")
    public String toRegularMemberList() {
        return "/back/memberCenter/regularMember/regularMemberList";
    }

    @RequestMapping(value = "/toVerifiedMemberList.action",method = RequestMethod.GET)
    @RequiresPermissions("menu:memberCenter:verifiedMember")
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到认证会员列表页面")
    public String toVerifiedMemberList() {
        return "/back/memberCenter/verifiedMember/verifiedMemberList";
    }



    @RequestMapping(value = "/queryGuestList.action",method = RequestMethod.POST)
    @RequiresPermissions("menu:memberCenter:guest")
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询游客列表")
    public BaseResponse queryGuestList(Model model,MemberVO memberVO, QueryPage queryPage){
        logger.info("开始查询游客，请求参数:{}", JSON.toJSONString(memberVO));
        BaseResponse<MemberDO> backResponse=new BaseResponse<>();
        try {

            MemberDomain memberDomain= ModelConvert.memberVO2MemberDomain(memberVO);
            memberDomain.setMemberType(MemberTypeEnum.GUEST.getCode());
            memberDomain.setQueryPage(queryPage);
            List<MemberDO> memberDOList= memberService.queryMemberList(memberDomain);
            backResponse.setResultList(memberDOList);
            backResponse.setQueryPage(memberDomain.getQueryPage());
            backResponse.setTotalRecord(memberDOList.size());
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"游客查询失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"游客查询失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("游客查询失败");
        }
        logger.info("结束查询游客，返回数据:{}", model);

        return backResponse;
    }

    @RequestMapping(value = "/queryRegularMemberList.action",method = RequestMethod.POST)
    @RequiresPermissions("menu:memberCenter:regularMember")
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询普通会员列表")
    public BaseResponse queryRegularMemberList(Model model,MemberVO memberVO, QueryPage queryPage){
        logger.info("开始查询会员，请求参数:{}", JSON.toJSONString(memberVO));
        BaseResponse<MemberDO> backResponse=new BaseResponse<>();

        try {

            MemberDomain memberDomain= ModelConvert.memberVO2MemberDomain(memberVO);
            memberDomain.setMemberType(MemberTypeEnum.REGULAR_MEMBER.getCode());
            memberDomain.setQueryPage(queryPage);
            List<MemberDO> memberDOList= memberService.queryMemberList(memberDomain);
            backResponse.setResultList(memberDOList);
            backResponse.setQueryPage(memberDomain.getQueryPage());
            backResponse.setTotalRecord(memberDOList.size());
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"会员查询失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"会员查询失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("会员查询失败");
        }
        logger.info("结束查询会员，返回数据:{}", model);

        return backResponse;
    }

    @RequestMapping(value = "/queryVerifiedMemberList.action",method = RequestMethod.POST)
    @RequiresPermissions("menu:memberCenter:verifiedMember")
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询认证会员列表")
    public BaseResponse queryVerifiedMemberList(Model model,MemberVO memberVO, QueryPage queryPage){
        logger.info("开始查询会员，请求参数:{}", JSON.toJSONString(memberVO));
        BaseResponse<MemberDO> backResponse=new BaseResponse<>();
        try {
            MemberDomain memberDomain= ModelConvert.memberVO2MemberDomain(memberVO);
            memberDomain.setMemberType(MemberTypeEnum.VERIFIED_MEMBER.getCode());
            memberDomain.setQueryPage(queryPage);
            List<MemberDO> memberDOList= memberService.queryMemberList(memberDomain);
            backResponse.setResultList(memberDOList);
            backResponse.setQueryPage(memberDomain.getQueryPage());
            backResponse.setTotalRecord(memberDOList.size());
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"会员查询失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"会员查询失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("会员查询失败");
        }
        logger.info("结束查询会员，返回数据:{}", model);

        return backResponse;
    }

    @RequestMapping(value = "/updateMember.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="更新会员")
    public BaseResponse updateMember(HttpServletRequest request, Model model,MemberVO memberVO){
        logger.info("开始更新会员，请求参数:{}", JSON.toJSONString(memberVO));
        BaseResponse<MemberDO> backResponse=new BaseResponse<>();

        try {
            MemberParamsChecker.checkUpdateMember(memberVO);
            MemberDomain memberDomain= ModelConvert.memberVO2MemberDomain(memberVO);
            if(MapCacheUtil.lock(memberVO.getId()+"")) {
                MemberDO memberDO = memberService.updateMember(memberDomain);
                BeanConverterUtil.copyProperties(memberVO, memberDO);
                model.addAttribute("memberVO", memberVO);
            }else {
                throw new BusinessException("该会员正在被操作中，请稍后再试!");
            }
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"会员更新失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"会员更新失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("会员查询失败");
        }finally {
            MapCacheUtil.unlock(memberVO.getId()+"");

        }
        logger.info("结束更新会员，返回数据:{}", model);
        return  backResponse;

    }

    @RequestMapping(value = "/memberRegister.action",method = RequestMethod.POST)
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="注册会员")
    public String register(HttpServletRequest request, Model model,MemberVO memberVO){
        logger.info("开始注册会员，请求参数:{}", JSON.toJSONString(memberVO));

        try {
            HttpSession session=request.getSession();
            Object openid=session.getAttribute(CommonConstants.OPENID);
            if(null!=openid){
                memberVO.setOpenid((String)openid);
            }
            MemberParamsChecker.checkRegisterMember(memberVO);
            MemberDomain memberDomain= ModelConvert.memberVO2MemberDomain(memberVO);
         /*   WxUserInfo wxUserInfo= WechatClient.getUserInfo(memberVO.getOpenid());
            if(null==wxUserInfo||null==wxUserInfo.getOpenid()){
                throw new BusinessException("未获取到微信用户信息!");
            }*/
           //todo 测试
            WxUserInfo wxUserInfo=new WxUserInfo();
            wxUserInfo.setSex(1);
            wxUserInfo.setCity("昌吉");
            wxUserInfo.setCountry("呼图壁");
            wxUserInfo.setProvince("新疆");
            wxUserInfo.setHeadimgurl("http://wx.qlogo.cn/mmopen/xbIQx1GRqdvyqkMMhEaGOX802l1CyqMJNgUzKP8MeAeHFicRDSnZH7FY4XB7p8XHXIf6uJA2SCun");
            wxUserInfo.setLanguage("zh_CN");
            wxUserInfo.setOpenid("opWZdxNypXW9LDm-4D36nx1HyJfI");
            wxUserInfo.setNickname("雷霆");
            wxUserInfo.setSubscribe(1);
            wxUserInfo.setSubscribe_time(1434093047);
            //ModelConvert.wxUserInfo2MemberDomain(memberDomain,wxUserInfo);

            if(MapCacheUtil.lock(memberVO.getOpenid())){
                Long memberId= memberService.register(memberDomain);
                memberVO.setId(memberId);
                model.addAttribute("memberVO",memberVO);
            }else{
                throw new BusinessException("该请求正在处理中，请稍后再试!");
            }
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"会员注册失败，失败原因：",e1);
            model.addAttribute("errorInfo","会员注册失败："+e1.getMessage());
            return  "/front/error";
        }catch (Exception e2){
            model.addAttribute("errorInfo","会员注册失败,请稍后重试!");
            logger.error(LOG_PREFIX+"会员注册失败,失败原因",e2);
            return "/front/error";
        }finally {
            MapCacheUtil.unlock(memberVO.getOpenid());
        }


        logger.info("结束注册会员，返回数据:{}", model);

        return  "redirect:/front/memberCenter/toIndex.action";

    }

    @RequestMapping(value = "/applyMemberAuth.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="会员认证")
    public BaseResponse applyMemberAuth(HttpServletRequest request, Model model,MemberAuthenticationInfoVO memberAuthenticationInfoVO){
        logger.info("开始会员认证，请求参数:{}", JSON.toJSONString(memberAuthenticationInfoVO));

        BaseResponse<MemberAuthenticationInfoVO> response=new BaseResponse<>();

        try {
           // MemberParamsChecker.checkMemberAuth(memberAuthenticationInfoVO);
            HttpSession session = request.getSession();
            Object memberId=session.getAttribute(CommonConstants.MEMBER_ID);
            if(null!=memberId){
                memberAuthenticationInfoVO.setMemberId((Long)memberId);
            }
            model.addAttribute("memberAuthenticationInfoVO",memberAuthenticationInfoVO);
            MemberAuthenticationInfoDomain memberAuthenticationInfoDomain= ModelConvert.memberVO2MemberAuthenticationInfoDomain(memberAuthenticationInfoVO);
           // if(MapCacheUtil.lock(memberAuthenticationInfoVO.getMemberId()+"")){
               memberService.applyMemberAuth(memberAuthenticationInfoDomain);
           // }else{
            //    throw new BusinessException("该请求正在处理中，请稍后再试!");
           // }
            response.setSuccess(true);
            response.setMessage("提交认证成功!");
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"提交会员认证失败，失败原因：",e1);
            response.setSuccess(false);
            response.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"提交会员认证失败,失败原因",e2);
            response.setSuccess(false);
            response.setMessage("提交会员认证失败");
        }finally {
          //  MapCacheUtil.unlock(memberAuthenticationInfoVO.getMemberId() + "");
        }

        logger.info("结束会员认证，返回数据:{}", model);

        return  response;
    }




    @RequestMapping(value = "/queryMemberDetail.action",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("menu:memberCenter:queryMemberDetail")
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询会员")
    public BaseResponse queryMemberDetail(Model model,MemberVO memberVO){
        BaseResponse<MemberVO> backResponse=new BaseResponse();

        logger.info("开始查询会员，请求参数:{}", JSON.toJSONString(memberVO));

        try {
            MemberParamsChecker.checkQueryMember(memberVO);
            MemberDomain memberDomain= ModelConvert.memberVO2MemberDomain(memberVO);
            MemberDO memberDO= memberService.queryMember(memberDomain);
            if(null!=memberDO){
                BeanConverterUtil.copyProperties(memberVO, memberDO);
            }
            backResponse.setResult(memberVO);
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);

        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"会员查询失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"会员查询失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("会员查询失败");
        }
        logger.info("结束查询会员，返回数据:{}", model);
        return  backResponse;

    }

}